package com.example.apng;

import android.content.Context;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import com.linecorp.apng.ApngDrawable;
import com.linecorp.apng.decoder.ApngException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ApngDrawableManager {

    private Context mContext;
    private ApngDrawableStore apngDrawableStore = new ApngDrawableStore();
    private static ApngDrawableManager instance;

    private ApngDrawableManager(Context context) {
        mContext = context;

    }

    public static ApngDrawableManager getInstance(@NonNull Context context) {
        if (instance == null) {
            instance = new ApngDrawableManager(context.getApplicationContext());
        }
        return instance;
    }

    private String getKey(int resId, int targetWidth, int targetHeight) {
        return resId + "_" + targetWidth + "_" + targetHeight;
    }

    /**
     *
     * @param resId
     * @param targetWidth 用户期待的宽度
     * @param targetHeight 用户期待的高度
     * @return
     */
    @WorkerThread
    @Nullable
    public ApngDrawable getApngDrawable(@DrawableRes int resId, int targetWidth, int targetHeight) {
        if (resId == -1) {
            return null;
        }
        String key = getKey(resId, targetWidth, targetHeight);
        ApngDrawable apngDrawable = apngDrawableStore.get(key);
        if (apngDrawable != null) {
            if (!apngDrawable.isRunning()) {
                apngDrawable.start();
            }
            return apngDrawable;
        }

        try {
            if (!isApng(mContext, resId)) {
                //图片类型不是APNG直接返回失败
                return null;
            }
            if (targetWidth <= 0 || targetHeight <= 0) {
                apngDrawable = ApngDrawable.Companion.decode(mContext.getResources(), resId, null, null);
            } else {
                apngDrawable = ApngDrawable.Companion.decode(mContext.getResources(), resId, targetWidth, targetHeight);
            }
            apngDrawable.start();
            apngDrawableStore.put(key, apngDrawable);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return apngDrawable;
    }

    @WorkerThread
    public static boolean isApng(@NonNull Context context, @DrawableRes int resId) {
        return ApngDrawable.Companion.isApng(context.getResources(), resId);
    }

}
